package ca.concordia.soen6461.wichf.dao.mem;

import java.util.Comparator;
import java.util.Date;
import java.util.List;

import ca.concordia.soen6461.wichf.dao.ScheduledEventDao;
import ca.concordia.soen6461.wichf.dao.memdb.Predicate;
import ca.concordia.soen6461.wichf.entity.ScheduledEvent;
import ca.concordia.soen6461.wichf.entity.User;

public class ScheduledEventMemDao implements ScheduledEventDao {

	private Comparator<ScheduledEvent> defaultOrder = new Comparator<ScheduledEvent>() {
		
		@Override
		public int compare(ScheduledEvent e1, ScheduledEvent e2) {
			return e1.getFrom().compareTo(e2.getFrom());
		}
		
	};
	
	public ScheduledEventMemDao() {
	}

	@Override
	public ScheduledEvent delete(User user, Date from) {
		ScheduledEvent e = new ScheduledEvent();
		e.setUser(user);
		e.setFrom(from);
		return DB.scheduledEventTable.delete(e);
	}

	@Override
	public void save(ScheduledEvent event) {
		DB.scheduledEventTable.save(event);
	}

	@Override
	public List<ScheduledEvent> find(final Date date) {
		return find(date, date);
	}

	@Override
	public List<ScheduledEvent> find(final User user) {
		return DB.scheduledEventTable.find(new Predicate<ScheduledEvent>() {
			
			@Override
			public boolean matches(ScheduledEvent value) {
				return value.getUser().getId().equals(user.getId());
			}
			
		}, defaultOrder);
	}

	@Override
	public List<ScheduledEvent> find(final Date from, final Date to) {
		return DB.scheduledEventTable.find(new Predicate<ScheduledEvent>() {
			
			@Override
			public boolean matches(ScheduledEvent value) {
				boolean fromLessThanDate = value.getFrom().compareTo(from) <= 0;
				boolean dateLessThanTo = to.compareTo(value.getTo()) < 0;
				return fromLessThanDate && dateLessThanTo;
			}
			
		}, defaultOrder);
	}

	@Override
	public List<ScheduledEvent> find(final Date from, final Date to, final User user, final ScheduledEvent.Type type) {
		return DB.scheduledEventTable.find(new Predicate<ScheduledEvent>() {
			
			@Override
			public boolean matches(ScheduledEvent value) {
				boolean fromLessThanDate = value.getFrom().compareTo(from) <= 0;
				boolean dateLessThanTo = to.compareTo(value.getTo()) < 0;
				boolean sameUser = user.getName().equals(value.getUser().getName());
				boolean sameType = type.equals(value.getType());
				return fromLessThanDate && dateLessThanTo && sameUser && sameType;
			}
			
		}, defaultOrder);
	}

}
